package com.example.utils;

import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * jdbc操作类
 *
 * @className: JdbcUtils
 * @author: chentao
 * @date: 2025/9/25 12:59
 * @Version: 1.0
 * @description:
 */
@Data
public class JdbcUtils {

    Logger logger = LoggerFactory.getLogger(getClass());

    private String host;

    private int port;

    private String db;

    private String username;

    private String password;

    private String driverClassName;

    public JdbcUtils(String host, int port, String db, String username, String password, String driverClassName) {
        this.host = host;
        this.port = port;
        this.db = db;
        this.username = username;
        this.password = password;
        this.driverClassName = driverClassName;
    }

    public static Connection getConnection(String host, int port, String db, String username, String password, String driverClassName) throws Exception {
        Class.forName(driverClassName);
        return DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + db, username, password);
    }

    public Connection getConnection() throws Exception {
        Class.forName(driverClassName);
        return DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + db, username, password);
    }

    public List<Map<String, Object>> executeQuery(String sql) {
        List<Map<String, Object>> result = new ArrayList<>();
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            connection = getConnection();
            statement = connection.createStatement();
            resultSet = statement.executeQuery(sql);
            while (resultSet.next()) {
                Map<String, Object> row = new HashMap<>();
                for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
                    row.put(resultSet.getMetaData().getColumnName(i), resultSet.getObject(i));
                }
                result.add(row);
            }
        } catch (Exception e) {
            logger.error("执行SQL查询失败", e);
        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    logger.error("关闭数据库连接失败", e);
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    logger.error("关闭数据库连接失败", e);
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (Exception e) {
                    logger.error("关闭数据库连接失败", e);
                }
            }
        }
        return result;
    }
}
